/*
 *    Copyright 2019 CManLH
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.lifeonwalden.fa4py;

import com.lifeonwalden.fa4py.common.DicItem;
import com.lifeonwalden.fa4py.common.constant.UnicodeRange;

public class PinYinDictionary {
    private DicItem[] items;

    public void init() {
        String[][] dicItems = new Builder().build();
        this.items = new DicItem[UnicodeRange.MAX_CODE - UnicodeRange.MIN_CODE + 1];
        int ctxCount = dicItems.length;
        for (int i = 0; i < this.items.length; i++) {
            char[][] _alphabets = new char[ctxCount][];
            boolean hasData = false;
            for (int ctxIdx = 0; ctxIdx < ctxCount; ctxIdx++) {
                char[] alphabets = parse(dicItems[ctxIdx][i]);
                if (null != alphabets) {
                    _alphabets[ctxIdx] = alphabets;
                    hasData = true;
                }
            }
            if (hasData) {
                this.items[i] = new DicItem(_alphabets);
            }
        }
    }

    public char[] get(char _char) {
        return get(_char, -1);
    }

    public char[] get(char _char, int contextNumber) {
        if (_char < UnicodeRange.MIN_CODE || _char > UnicodeRange.MAX_CODE) {
            return new char[]{_char};
        }

        return this.items[_char - UnicodeRange.MIN_CODE].getAlphabet(contextNumber);
    }

    public char[][] get(String words) {
        return get(words, -1);
    }

    public char[][] get(String words, int contextNumber) {
        char[][] alphabets = new char[words.length()][];
        for (int i = 0; i < alphabets.length; i++) {
            alphabets[i] = get(words.charAt(i), contextNumber);
        }

        return alphabets;
    }

    private char[] parse(String alphabet) {
        if (null != alphabet && !alphabet.isEmpty()) {
            if (1 == alphabet.length()) {
                return new char[]{alphabet.charAt(0)};
            } else {
                char[] _alphabets = new char[(alphabet.length() + 1) / 2];
                int _idx = 0;
                for (int idx = 0; idx < alphabet.length(); idx++) {
                    char _char = alphabet.charAt(idx);
                    if (_char >= 'a' && _char <= 'z') {
                        _alphabets[_idx++] = _char;
                    }
                }
                return _alphabets;
            }
        }

        return null;
    }
}
